package cn.newstrength.shihaipeng.step;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Map;

import cn.newstrength.shihaipeng.data.SHPSampleObj;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
//import cn.newstrength.sample.data.SampleObj;
import cn.newstrength.wtdf.plugin.service.RedisService;
import cn.newstrength.wtdf.plugin.util.TranUtils;
import cn.newstrength.wtdf.web.processor.Operation;
import cn.newstrength.wtdf.web.processor.OperationStep;

public class RedisStep implements OperationStep {
	
	private static final Logger logger = LoggerFactory.getLogger(RedisStep.class);
	
	@Override
	public int excute(Operation oper) {
		/*
		 * 获取 Redis 服务
		 */
		RedisService redisService = oper.getBean("redisService", RedisService.class);
		/*
		 * 存储字符串
		 */
		redisService.put("cn:newstrength:nsms.sample.string", "Hi redis!",30);//30秒后删除
		logger.info("Redis value：{}",TranUtils.toJson(redisService.get("cn:newstrength:nsms.sample.string")));
		/*
		 * 存储对象
		 */
		SHPSampleObj sampleObj = new SHPSampleObj();
		sampleObj.setId(1);
		sampleObj.setName("王新栋");
		sampleObj.setCode("10001");
		redisService.put("cn:newstrength:nsms.sample.bean", sampleObj,30);//30秒后删除
		Object value = redisService.get("cn:newstrength:nsms.sample.bean");
		logger.info("Redis value：{}",TranUtils.toJson(value));
		/*
		 * 存储文件
		 */
		File file = new File("/home/koma/sample.txt");
		if (file.exists()) {
			try (FileInputStream fs = new FileInputStream(file);) {
				byte[] array = IOUtils.toByteArray(fs);
				redisService.put("cn:newstrength:nsms.sample.file", array, 30);// 30秒后删除
			} catch (IOException e) {
				logger.error("缓存文件发生异常了：",e);
			}
		}
		/*
		 * 回传数据
		 */
		oper.setTranStepSuccResult("存储字符串、SampleObj对象，File对象成功，请查看节点 cn:newstrength:nsms.sample （TTL 30S）");
		return 0;
	}

	@Override
	public int init(Map<String, String> arg0) {
		return 0;
	}
}

